//
//  XRChatToolbar.m
//  YWBaseFrameWork
//
//  Created by 余伟 on 2017/1/22.
//  Copyright © 2017年 NeiQuan. All rights reserved.
//

#import "XRChatToolbar.h"
@interface XRChatToolbar ()<UITextViewDelegate>
{
    UIButton         *_sendButton;//发送按钮
    UIButton         *_shareButton;//分享按钮
    UIView           *_toolbarView;
    CGFloat           _version;
    //上一次inputTextView的contentSize.height
    CGFloat           _previousTextViewContentHeight;
    NSMutableArray    *_rightItemArray;
}
@end

@implementation XRChatToolbar

-(void)dealloc
{
    _inputTextView.delegate=nil;
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}
- (instancetype)initWithFrame:(CGRect)frame
{
    if (self=[self initWithFrame:frame horizontalPadding:8 verticalPadding:5 inputViewMinHeight:36 inputViewMaxHeight:150])
    {
        
        
    }
    return self;
}
- (instancetype)initWithFrame:(CGRect)frame
            horizontalPadding:(CGFloat)horizontalPadding
              verticalPadding:(CGFloat)verticalPadding
           inputViewMinHeight:(CGFloat)inputViewMinHeight
           inputViewMaxHeight:(CGFloat)inputViewMaxHeight
{
    if (frame.size.height < (verticalPadding * 2 + inputViewMinHeight)) {
        frame.size.height = verticalPadding * 2 + inputViewMinHeight;
    }
    self = [super initWithFrame:frame];
    if (self) {
        _horizontalPadding = horizontalPadding;
        _verticalPadding = verticalPadding;
        _inputViewMinHeight = inputViewMinHeight;
        _inputViewMaxHeight = inputViewMaxHeight;
        _version = [[[UIDevice currentDevice] systemVersion] floatValue];

        [self addOwnViews];
        
        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(chatKeyboardWillChangeFrame:) name:UIKeyboardWillChangeFrameNotification object:nil];
    
    }
    return self;

}
#pragma mark 添加子视图
-(void)addOwnViews
{
    
    //toolbar
    _toolbarView = [[UIView alloc] initWithFrame:self.bounds];
    _toolbarView.backgroundColor = [UIColor clearColor];
    [self addSubview:_toolbarView];
    
    //输入框
    _inputTextView = [[XRPlaceHolderTextView alloc] initWithFrame:CGRectMake(self.horizontalPadding, self.verticalPadding, self.frame.size.width - self.verticalPadding * 2, self.frame.size.height - self.verticalPadding * 2)];
    _inputTextView.autoresizingMask = UIViewAutoresizingFlexibleHeight;
    _inputTextView.scrollEnabled = YES;
    _inputTextView.returnKeyType = UIReturnKeySend;
    _inputTextView.enablesReturnKeyAutomatically = YES; // UITextView内部判断send按钮是否可以用
    _inputTextView.placeHolder = @"输入评论内容";
    _inputTextView.delegate = self;
    _inputTextView.backgroundColor = [UIColor clearColor];
    _inputTextView.layer.borderColor = [UIColor colorWithWhite:0.8f alpha:1.0f].CGColor;
    _inputTextView.layer.borderWidth = 0.65f;
    _inputTextView.layer.cornerRadius = 6.0f;
    _previousTextViewContentHeight = [self _getTextViewContentH:_inputTextView];
    [_toolbarView addSubview:_inputTextView];
    
    //发送按钮
    _sendButton=[UIButton  buttonWithType:UIButtonTypeCustom];
    [_sendButton setTitleColor:kWhiteColor forState:UIControlStateNormal];
    [_sendButton setTitle:@"发送" forState:UIControlStateNormal];
    [_sendButton setFrame:CGRectMake(0, 0, 40, 0)];
    _sendButton.autoresizingMask = UIViewAutoresizingFlexibleTopMargin;
    [_sendButton setBackgroundColor:kNavBarThemeColor];
    _sendButton.layer.cornerRadius=5.0f;
    _sendButton.layer.masksToBounds=YES;
    _sendButton.titleLabel.font=[UIFont systemFontOfSize:13];
    _rightItemArray=[[NSMutableArray alloc] init];
    [_sendButton addTarget:self action:@selector(clicksendButton:) forControlEvents:UIControlEventTouchUpInside];
    [_rightItemArray addObject:_sendButton];
    
    CGFloat oMaxX = _toolbarView.frame.size.width - self.horizontalPadding;
    
    CGFloat itemHeight = _toolbarView.frame.size.height - self.verticalPadding * 2;
    
    
    if ([_rightItemArray count] > 0) {
        for (NSInteger i = (_rightItemArray.count - 1); i >= 0; i--) {
            UIButton *item = [_rightItemArray objectAtIndex:i];
            
            if ([item isKindOfClass:[UIButton class]]) {
                UIButton *chatItem = (UIButton *)item;
                if (chatItem) {
                    CGRect itemFrame = chatItem.frame;
                    if (itemFrame.size.height == 0) {
                        itemFrame.size.height = itemHeight;
                    }
                    
                    if (itemFrame.size.width == 0) {
                        itemFrame.size.width = itemFrame.size.height;
                    }
                    
                    oMaxX -= itemFrame.size.width;
                    itemFrame.origin.x = oMaxX;
                    itemFrame.origin.y = (_toolbarView.frame.size.height - itemFrame.size.height) / 2;
                    chatItem.frame = itemFrame;
                    oMaxX -= self.horizontalPadding;
                    
                    [_toolbarView addSubview:chatItem];
                }
            }
        }
    }
    
    CGRect inputFrame = self.inputTextView.frame;
    CGFloat value = oMaxX - CGRectGetMaxX(inputFrame);
    inputFrame.size.width += value;
    self.inputTextView.frame = inputFrame;
}
#pragma mark - private input view

- (CGFloat)_getTextViewContentH:(UITextView *)textView
{
    if (_version >= 7.0)
    {
        return ceilf([textView sizeThatFits:textView.frame.size].height);
    } else {
        return textView.contentSize.height;
    }
}
#pragma mark - UIKeyboardNotification

- (void)chatKeyboardWillChangeFrame:(NSNotification *)notification
{
    NSDictionary *userInfo = notification.userInfo;
    CGRect endFrame = [userInfo[UIKeyboardFrameEndUserInfoKey] CGRectValue];
    CGRect beginFrame = [userInfo[UIKeyboardFrameBeginUserInfoKey] CGRectValue];
    CGFloat duration = [userInfo[UIKeyboardAnimationDurationUserInfoKey] doubleValue];
    UIViewAnimationCurve curve = [userInfo[UIKeyboardAnimationCurveUserInfoKey] integerValue];
    
    void(^animations)() = ^{
        [self _willShowKeyboardFromFrame:beginFrame toFrame:endFrame];
    };
    
    [UIView animateWithDuration:duration delay:0.0f options:(curve << 16 | UIViewAnimationOptionBeginFromCurrentState) animations:animations completion:nil];
}
- (void)_willShowKeyboardFromFrame:(CGRect)beginFrame toFrame:(CGRect)toFrame
{
    if (beginFrame.origin.y == [[UIScreen mainScreen] bounds].size.height)
    {
       [self _willShowBottomHeight:toFrame.size.height];

    }
    else if (toFrame.origin.y == [[UIScreen mainScreen] bounds].size.height)
    {
        [self _willShowBottomHeight:0];
    }
    else
    {
      [self _willShowBottomHeight:toFrame.size.height];
    }
}
- (void)_willShowInputTextViewToHeight:(CGFloat)toHeight
{
    if (toHeight < self.inputViewMinHeight) {
        toHeight = self.inputViewMinHeight;
    }
    if (toHeight > self.inputViewMaxHeight) {
        toHeight = self.inputViewMaxHeight;
    }
    
    if (toHeight == _previousTextViewContentHeight)
    {
        return;
    }
    else
    {
        CGFloat changeHeight = toHeight - _previousTextViewContentHeight;
        
        CGRect rect = self.frame;
        rect.size.height += changeHeight;
        rect.origin.y -= changeHeight;
        self.frame = rect;
        
        rect = _toolbarView.frame;
        rect.size.height += changeHeight;
        _toolbarView.frame = rect;
        
        if (_version < 7.0) {
            [self.inputTextView setContentOffset:CGPointMake(0.0f, (self.inputTextView.contentSize.height - self.inputTextView.frame.size.height) / 2) animated:YES];
        }
        _previousTextViewContentHeight = toHeight;
        
    }
}

#pragma mark - private bottom view

- (void)_willShowBottomHeight:(CGFloat)bottomHeight
{
    CGRect fromFrame = self.frame;
    CGFloat toHeight = _toolbarView.frame.size.height + bottomHeight;
    CGRect toFrame = CGRectMake(fromFrame.origin.x, fromFrame.origin.y + (fromFrame.size.height - toHeight), fromFrame.size.width, toHeight);
    //如果需要将所有扩展页面都隐藏，而此时已经隐藏了所有扩展页面，则不进行任何操作
    if(bottomHeight == 0 && self.frame.size.height == _toolbarView.frame.size.height)
    {
        return;
    }
    self.frame = toFrame;
    
}
- (void)_willShowBottomView:(UIView *)bottomView
{
    
    
}
#pragma mark - UITextViewDelegate

- (BOOL)textViewShouldBeginEditing:(UITextView *)textView
{
    if ([self.delegate respondsToSelector:@selector(inputTextViewWillBeginEditing:)]) {
        [self.delegate inputTextViewWillBeginEditing:self.inputTextView];
    }

    return YES;
}

- (void)textViewDidBeginEditing:(UITextView *)textView
{
    [textView becomeFirstResponder];
    
    if ([self.delegate respondsToSelector:@selector(inputTextViewDidBeginEditing:)]) {
        [self.delegate inputTextViewDidBeginEditing:self.inputTextView];
    }
}

- (void)textViewDidEndEditing:(UITextView *)textView
{
    [textView resignFirstResponder];
}

- (BOOL)textView:(UITextView *)textView shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)text
{
    if ([text isEqualToString:@"\n"]) {
        if ([self.delegate respondsToSelector:@selector(didsendMessage:view:)]) {
            [self.delegate didsendMessage:textView.text view:self];
            self.inputTextView.text = @"";
            [self _willShowInputTextViewToHeight:[self _getTextViewContentH:self.inputTextView]];
        }
        
        return NO;
    }
    return YES;
}

- (void)textViewDidChange:(UITextView *)textView
{
    [self _willShowInputTextViewToHeight:[self _getTextViewContentH:textView]];
}

-(void)clicksendButton:(UIButton *)sendButton
{
    [_inputTextView  resignFirstResponder];
    if ([self.delegate respondsToSelector:@selector(didsendMessage:view:)]) {
        [self.delegate didsendMessage:_inputTextView.text view:self];
         self.inputTextView.text = @"";
        [self _willShowInputTextViewToHeight:[self _getTextViewContentH:self.inputTextView]];
    }
}
-(NSMutableAttributedString*)backspaceText:(NSMutableAttributedString*) attr length:(NSInteger)length
{
    NSRange range = [self.inputTextView selectedRange];
    if (range.location == 0) {
        return attr;
    }
    [attr deleteCharactersInRange:NSMakeRange(range.location - length, length)];
    return attr;
}
@end
